//
//  ZLoadHTMLViewController.m
//  ZT_iOS
//
//  Created by 周 光辉 on 2017/5/20.
//  Copyright © 2017年 Brigitte. All rights reserved.
//

#import "ZLoadHTMLViewController.h"
#import <WebKit/WebKit.h>
//#import "ReaderViewController.h"

//#import "LSYReadViewController.h"
//#import "LSYReadPageViewController.h"
//#import "LSYReadUtilites.h"
//#import "LSYReadModel.h"
#import "NSString+ZTUrl.h"
#import "NSObject+ZTNotNull.h"
#import "ZTMacros.h"
#import "UIViewController+ZTHUD.h"
#import "Masonry.h"
#import "ZTUserInfoManage.h"

@interface ZLoadHTMLViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView * webView;
@property (nonatomic, copy) NSString * dataUrl;//加载的url

@property (nonatomic,strong)UIButton *isSelectBtn;
@end

@implementation ZLoadHTMLViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    WKWebView * view = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height-44-statusHeight)];
    view.navigationDelegate=self;
    view.allowsBackForwardNavigationGestures=YES;
    NSString * urlTest;
    _dataUrl = _url;
    if ([self hasChinese:_url]) {
        //处理URL中包含中文的情况
        urlTest =  [_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }else{
        urlTest = _url;
    }
//    if ([urlTest hasSuffix:@".txt"]) {
//
//    }
    [view loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlTest]]];
    NSLog(@"-%@",urlTest);
    self.webView = view;
    self.webView.userInteractionEnabled = YES;
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
//    self.webView.scrollView.scrollEnabled = NO;
    [self.view addSubview:view];
    [self showHudInView:self.view hint:@"加载中..."];

    if ([self.type isEqualToString:@"1"]) {
        view.frame = CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height);
        [self.view addSubview:self.isSelectBtn];
        [self.isSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top).offset(zStatusBarHeight+11);
            make.right.equalTo(self.view).offset(-20);
            make.width.and.height.equalTo(@22);
        }];
        if (![_url isNotEmpty]) {
            [self hideHud];
//            [self showHUDOnlyText:@"可在工作台界面打开"];
        }
    }else if ([self.type isEqualToString:@"2"]) {
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            
            if (@available(iOS 11.0, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            } else {
                make.top.equalTo(self.view);
            }
            make.left.right.bottom.equalTo(self.view);
        }];
        
    }else{
        
        /** bundle 引用*/
        NSBundle *associateBunle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"ZTPrivateLib" ofType:@"bundle"]];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"chat_back"
                                                                                                   inBundle: associateBunle
                                                                                                 compatibleWithTraitCollection:nil] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:(UIBarButtonItemStylePlain) target:self action:@selector(backClick)];
    }

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveClick) name:@"downLoadPDFFile" object:nil];
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backClick) name:@"epubFileBack" object:nil];

    //如果正在看书
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic) name:@"stopMusicNotificationCenter" object:nil];
    if ([self.type isEqualToString:@"2"]) {
        [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"webViewBackUpMethods"];
    }

}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"webViewBackUpMethods"]){//返回测试
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
-(UIButton *)isSelectBtn
{
    if (!_isSelectBtn) {
        _isSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSBundle *associateBunle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"ZTPrivateLib" ofType:@"bundle"]];

        [_isSelectBtn setBackgroundImage:[UIImage imageNamed:@"dcqzjwChaHao"
                                                    inBundle: associateBunle
                                                  compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
//        [_isSelectBtn setImage:[UIImage imageNamed:@"dcqzjwChaHao"] forState:UIControlStateNormal];
//        [_isSelectBtn setImage:[UIImage imageNamed:@"dcqzjwChaHao"] forState:UIControlStateSelected];
        [_isSelectBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    }
    return _isSelectBtn;
}
- (void)dismiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
//- (void)stopMusic
//{
//#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)
//
//    [self.navigationController popViewControllerAnimated:YES];
//
//#else // dismiss the modal view controller
//
//    [self dismissViewControllerAnimated:YES completion:NULL];
//
//#endif // DEMO_VIEW_CONTROLLER_PUSH
//
//    [self backClick];
//}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self deleteWebCache];
    if ([self.type isEqualToString:@"2"]) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    if ([self.type isEqualToString:@"2"]) {
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"webViewBackUpMethods"];
    }
}

- (void)deleteWebCache {
    
    if([[UIDevice currentDevice].systemVersion floatValue] >=9.0) {
        
        NSSet*websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        
        NSDate*dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        
        [[WKWebsiteDataStore defaultDataStore]removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
        
    }else{
        
        NSString*libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES)objectAtIndex:0];
        
        NSString*cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        
        NSError*errors;
        
        [[NSFileManager defaultManager]removeItemAtPath:cookiesFolderPath error:&errors];
        
    }
    
}

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSString * url;// = [self.webView.URL absoluteString];
//    NSString *urlString;
    if ([self hasChinese:[self.webView.URL absoluteString]]) {
        //处理URL中包含中文的情况
    
        url =  [[self.webView.URL absoluteString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }else{
        url = [self.webView.URL absoluteString];
    }
    NSLog(@"开始请求:%@",url);

    if ([url hasSuffix:@".pdf"]) {//hasPrefix

        NSString *path = [_dataUrl componentsSeparatedByString:@"Documents"].lastObject;
        NSString *fileNameString = [path componentsSeparatedByString:@"/"].lastObject;
        
        NSString *documentsPath =[self dataFilePath];
        NSString * urlTest1;
        if ([self hasChinese:url]) {// [model.url URLEncodedString]
            //处理URL中包含中文的情况
            
            urlTest1 =  [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }else{
            urlTest1 = url;
        }
        
        NSData * audioData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlTest1]];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsPath , fileNameString];
        NSString *filePath1 = [NSString stringWithFormat:@"%@/%@.pdf", documentsPath , self.navigationItem.title];

        [audioData writeToFile:filePath1 atomically:YES];
//        [self showHUDOnlyText:@"保存本地成功"];
        NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
//        ReaderDocument *document = [ReaderDocument withDocumentFilePath:filePath password:phrase];
//
//        if (document != nil) // Must have a valid ReaderDocument object in order to proceed with things
//        {
//            [self hideHud];
////
//            ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
//
//            readerViewController.delegate = self; // Set the ReaderViewController delegate to self
//
//#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)
//
//            [self.navigationController pushViewController:readerViewController animated:YES];
//
//#else // present in a modal view controller
//
//            readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//            readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
//
//            [self presentViewController:readerViewController animated:YES completion:NULL];
//
//#endif // DEMO_VIEW_CONTROLLER_PUSH
//        }
//        else // Log the error so that we know that something went wrong
//        {
//            NSLog(@"%s [ReaderDocument withDocumentFilePath:'%@' password:'%@'] failed.", __FUNCTION__, filePath, phrase);
//            [self hideHud];
//        }

//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"详情-更多"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick)];
//    }
//    else if ([url hasSuffix:@".txt"]){
//
//        NSString *path = [url componentsSeparatedByString:@"Documents"].lastObject;
//        NSString *fileNameString = [path componentsSeparatedByString:@"/"].lastObject;
//
//        NSString *documentsPath =[self dataFilePath];
//        NSData * audioData = [NSData dataWithContentsOfURL:self.webView.URL];
//        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsPath , fileNameString];
////        NSFileManager *fileManager = [NSFileManager defaultManager];
//
////        if(![fileManager fileExistsAtPath:filePath]){ //如果不存在
//
//        NSString *filePath1 = [NSString stringWithFormat:@"%@/%@.txt", documentsPath, self.navigationItem.title];
//
//        //        NSFileManager *fileManager = [NSFileManager defaultManager];
//
//        //        if(![fileManager fileExistsAtPath:filePath]){ //如果不存在
//        // 在Document目录下创建一个archiver目录
//        [audioData writeToFile:filePath1 atomically:YES];
//            // 在Document目录下创建一个archiver目录
////            [audioData writeToFile:filePath atomically:YES];
////        }
//
//        LSYReadPageViewController *pageView = [[LSYReadPageViewController alloc] init];
//        NSURL *fileURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", filePath]];
//
//        pageView.resourceURL = fileURL;    //文件位置
//
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
//
//            pageView.model = [LSYReadModel getLocalModelWithURL:fileURL];
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self hideHud];
//                [self presentViewController:pageView animated:YES completion:nil];
//            });
//        });
//
//    }
    }else if ([url hasSuffix:@".epub"]){

        NSString *path = [url componentsSeparatedByString:@"Documents"].lastObject;
        NSString *fileNameString = [path componentsSeparatedByString:@"/"].lastObject;
        
        NSString *documentsPath =[self dataFilePath];
        NSString * urlTest1;
        if ([self hasChinese:url]) {// [model.url URLEncodedString]
            //处理URL中包含中文的情况
            
            urlTest1 =  [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }else{
            urlTest1 = url;
        }
        
        NSData * audioData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlTest1]];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsPath, fileNameString];
//        NSString *path1 = [_dataUrl componentsSeparatedByString:@"Documents"].lastObject;
//        NSString *fileNameString1 = [path1 componentsSeparatedByString:@"/"].lastObject;
        
        //修改 解决打不开的问题
//        NSString *filePath1 = [NSString stringWithFormat:@"%@/%@.epub", documentsPath, self.navigationItem.title];

        
        NSString *filePath1;
        if ([fileNameString hasSuffix:@".epub"]) {
            filePath1 = [NSString stringWithFormat:@"%@/%@", documentsPath, fileNameString];
        }else{
            filePath1 = [NSString stringWithFormat:@"%@/%@.epub", documentsPath, fileNameString];
        }
        //        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //        if(![fileManager fileExistsAtPath:filePath]){ //如果不存在
        // 在Document目录下创建一个archiver目录
        [audioData writeToFile:filePath1 atomically:YES];
//        }
//
//        LSYReadPageViewController *pageView = [[LSYReadPageViewController alloc] init];
//        NSString * urlTest;
//        if ([self hasChinese:filePath1]) {// [model.url URLEncodedString]
//            //处理URL中包含中文的情况
//
//            urlTest =  [filePath1 stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//        }else{
//            urlTest = filePath1;
//        }
//        NSURL *fileURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", urlTest]];
//        pageView.resourceURL = fileURL;    //文件位置
//
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
//            pageView.model = [LSYReadModel getLocalModelWithURL:fileURL];
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self hideHud];
//                [self presentViewController:pageView animated:YES completion:nil];
//            });
//        });
//
    }else if ([url hasSuffix:@".word"] || [url hasSuffix:@".xlsx"] || [url hasSuffix:@".docx"] || [url hasSuffix:@".zip"] || [url hasSuffix:@".txt"]){

        self.navigationItem.rightBarButtonItem = nil;//[[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveClick)];//软测问题

    }else{

        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (BOOL)hasChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}
- (void)saveClick
{
//    NSString *path = [_dataUrl componentsSeparatedByString:@"Documents"].lastObject;
//    NSString *fileNameString = [path componentsSeparatedByString:@"/"].lastObject;

    NSString *documentsPath =[self dataFilePath];
    NSData * audioData = [NSData dataWithContentsOfURL:self.webView.URL];
    NSString *path = [_dataUrl componentsSeparatedByString:@"Documents"].lastObject;
    NSString *fileNameString = [path componentsSeparatedByString:@"/"].lastObject;
    NSArray *array = [fileNameString componentsSeparatedByString:@"."]; //从字符A中分隔成2个元素的数组
    
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsPath , self.navigationItem.title,array[1]];
    [audioData writeToFile:filePath atomically:YES];
    [self showHUDOnlyText:@"保存成功"];
}

#pragma mark -- 获取文件存储路径（其他类型）
-(NSString *)dataFilePath {
    
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory =  [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES) objectAtIndex:0];//[paths objectAtIndex:0];
    NSString *dataFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/HyphenateSDK/appdata/%@/gongzuotai1/",[[ZTUserInfoManage defaultService] getLoginUserAccount]]]; // 在Document目录下创建 "gongzuotai1" 文件夹
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];
    
    if (!(isDir && existed)) {
        // 在Document目录下创建一个archiver目录
        [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }

    return [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/HyphenateSDK/appdata/%@/gongzuotai1/",[[ZTUserInfoManage defaultService] getLoginUserAccount]]];
}
#pragma mark -- 保存pdf
-(NSString *)dataFilePath1 {
    
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES) objectAtIndex:0];//[paths objectAtIndex:0];
    NSString *dataFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/gongzuotai1/",[[ZTUserInfoManage defaultService] getLoginUserAccount]]]; // 在Document目录下创建 "gongzuotai1" 文件夹
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];
    
    if (!(isDir && existed)) {
        // 在Document目录下创建一个archiver目录
        [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/gongzuotai/",[[ZTUserInfoManage defaultService] getLoginUserAccount]]];
}

-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"提交数据");
    
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"请求完成");
    [self hideHud];
//    if ([self.webView canGoBack] == YES) {
//        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"chat_back"] style:(UIBarButtonItemStylePlain) target:self action:@selector(backClick1)];
//    }else{
        
        NSBundle *associateBunle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"ZTPrivateLib" ofType:@"bundle"]];

        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"chat_back"
                                                                                                    inBundle: associateBunle
                                                                                                  compatibleWithTraitCollection:nil] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:(UIBarButtonItemStylePlain) target:self action:@selector(backClick)];
//    }
    
//    if ([_dataUrl hasSuffix:@".txt"]) {
//        [self.webView goBack];
//        [self backClick];
//    }
    
}

- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backClick1
{
    [self.webView goBack];
}
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error//数据加载失败
{

    if ([_dataUrl hasSuffix:@".mobi"]){
        [self showHUDOnlyText:@"暂时无法支持mobi格式文件"];
        [self hideHud];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self backClick];
        });
    }else if ([_dataUrl hasSuffix:@".epub"]){
        [self showHUDOnlyText:@"正在打开,请稍后"];
    }else if ([_dataUrl hasSuffix:@".txt"]){
        [self showHUDOnlyText:@"正在打开,请稍后"];
    }else if ([_dataUrl hasSuffix:@".pdf"]){
        [self showHUDOnlyText:@"正在打开,请稍后"];
    }else{
        [self hideHud];
        if ([self.type isEqualToString:@"2"]) {
            [self showAlertViewWithTitle:@"网络不给力哦,请稍后再试" subTitle:nil confirmBtnTitle:@"确定" confirmBlock:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [self showHUDOnlyText:@"网络不给力哦,请稍后再试"];
        }
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - ReaderViewControllerDelegate methods
//
//- (void)dismissReaderViewController:(ReaderViewController *)viewController
//{
////    [self.webView goBack];
//#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)
//
//    [self.navigationController popViewControllerAnimated:YES];
//
//#else // dismiss the modal view controller
//
//    [self dismissViewControllerAnimated:YES completion:NULL];
//
//#endif // DEMO_VIEW_CONTROLLER_PUSH
//
//    [self backClick];
//
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
